// bignumber.js用于数字精度要求较高的计算。

import BigNumber from 'bignumber.js';

/**
 * 加法
 * @param num { number }
 * @param rest { number }
 * @return {number}
 */
export const add = (num, ...rest) => {
  if(Array.isArray(num)) {
      return BigNumber.sum.apply(null, num).toNumber()
  } else {
    let bn = new BigNumber(num)
    rest.forEach(item => {
        bn = new BigNumber(bn.plus(item))
    })
    return bn.toNumber()
  }
}

/**
 * 减法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const subtract = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.minus(item))
  })
  return bn.toNumber()
}

/**
 * 乘法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const multiply = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.multipliedBy(item))
  })
  return bn.toNumber()
}

/**
 * 除法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const divide = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.dividedBy(item))
  })
  return bn.toNumber()
}

/**
 * @description: 转换成千分位
 * @param num { number | string }
 * @param precision { number }
 * @return { number }
 */
export const toFormat = ( num, config = {
    prefix: '',
    decimalSeparator: '.',
    groupSeparator: ',',
    groupSize: 3
}) => {
  let bn = new BigNumber(num)
  return bn.toFormat(config)
}
/**
 * @description: 保留小数点后几位不够添0
 * @param {*}
 * @return {*}
 */
export const toFixed = (num, precision) => {
  let bn = new BigNumber(num)
  return bn.toFixed(precision, 1)
}
/**
 * @description: 保留小数点后几位
 * @param {*}
 * @return {*}
 */
export const toPrecision = (num, precision) => {
  let bn = new BigNumber(num)
  return bn.dp(precision, 1).toNumber()
}